package org.dromara.job.snailjob;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bean.constant.OrderStatusConstant;
import org.dromara.bean.domain.HisGoodsOrder;
import org.dromara.bean.mapper.HisGoodsOrderMapper;
import org.dromara.common.core.service.DictService;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
@JobExecutor(name = "goodsOrderShipped")
@RequiredArgsConstructor
@Slf4j
public class GoodsOrderShipped {
    private final HisGoodsOrderMapper goodsOrderMapper;


    public ExecuteResult jobExecute(JobArgs jobArgs) {
        log.info("定时完成已发货商城订单");

        LambdaQueryWrapper<HisGoodsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(HisGoodsOrder::getStatus, OrderStatusConstant.SHOP_SHIPPED);

        List<HisGoodsOrder> orderTreatList = goodsOrderMapper.selectList(lqw);
        Set<Integer> orderIds = Sets.newHashSet();
        List<HisGoodsOrder> updateList = Lists.newArrayList();
        for (HisGoodsOrder obj : orderTreatList) {
            Date endDate = DateUtil.offsetMinute(obj.getDeliveryTime(), 10081);
            // 超过7天未评价，自动完成订单
            if (DateUtil.date().after(endDate)) {
                orderIds.add(obj.getId().intValue());
                obj.setStatus( OrderStatusConstant.SHOP_EVALUATE);
                updateList.add(obj);
            }
        }
        if (CollUtil.isNotEmpty(updateList)) {
            goodsOrderMapper.updateBatchById(updateList);
        }
        log.info("订单已完成,订单ID:{}", orderIds);
        return ExecuteResult.success("完成");
    }
}
